﻿using AppDataStruct;
using BoardBroker;
using ComLib.ComType;
using ComUIControl;
using DeviceCommon;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json;
using System;
using System.Diagnostics;

namespace YSLPages
{
    public class ProcessReadIDCardInfo : PageProcessBase<ProcessReadIDCardInfo>
    {
        private BoardControl _board = null;
        private DeviceControl _device = null;
        public IDCardAll IDCardInfo { get; set; } = new IDCardAll();
        private ProcessReadIDCardInfo() : base()
        {
            _board = BoardControl.Instance;
        }
        public override void Init()
        {
            base.Init();
        }

        public override void Exit()
        {
            base.Exit();
        }

        public override void InitData()
        {
            base.InitData();
            _device = new DeviceControl("IDCardReader");
            _device.OnCatchException = OnCatchException;
            _device.OnWorkingDone = OnReadSuccess;
            _device.OnWorkingFailed = OnReadFailed;
            _device.OnTimeout = OnReadTimeout;
            if (!_device.Init())
            {
                MsgBox.Show($"设备管理器初始化失败:{_device.Error}");
            }
        }

        public override void UpdateData()
        {
            base.UpdateData();
            if (IDCardInfo == null)
            {
                Log.WriteAsync("获取身份证信息失败.");
                MsgBox.Show("获取身份证信息失败.");
                return;
            }
            if (MainPage != null)
            {
                if (MainPage.UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || MainPage.UserAction == UserApplyAction.TakePhotoAndYSL
                || MainPage.UserAction == UserApplyAction.OnlyYSL)
                {
                    SetSFZData();
                }
                
                string personDir = _config.OutputDirs[IDCardInfo.number];
                SetValue("PersonDataDirectory", personDir);
                SetValue("IDCardInfo", IDCardInfo);
            }
            
        }

        public override void StartWork()
        {
            //_board.SetLightFlash(DeviceType.IdCardReader);
            
            if (_device != null)
            {
                _device.Start();
            }
            base.StartWork();
        }

        public override void ClearData()
        {
            base.ClearData();
            if (_device != null)
            {
                _device.Stop();
                _device.Dispose();
                _device = null;
            }
            IDCardInfo = null;
        }

        public override void StopWork()
        {
            //_board.TurnOffLight(DeviceType.IdCardReader);
           
            if (_device != null)
            {
                _device.Stop();
            }
            base.StopWork();
        }

        public override void PlayWelcomeVoice()
        {
            base.PlayWelcomeVoice();
        }

        private void OnReadSuccess(string outParams)
        {
            StopWork();
            string msg = $"读取结果: \n{outParams}";
            Log.WriteAsync(msg);
            IDCardAll idcard = GetValue<IDCardAll>("IDCardInfo");
            if (idcard != null && !string.IsNullOrEmpty(idcard.number))
            {
                //身份证已经读取过了，不再处理
                Log.WriteAsync($"已经读取身份证到身份证{idcard.number},忽略读取结果");
                return;
            }

            try
            {
                // 在这里处理身份证信息解析结果
                IDCardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);
                if (IDCardInfo != null)
                {
                    IDCardInfo.address = IDCardInfo.address.Trim();
                    IDCardInfo.name = IDCardInfo.name.Trim();
                }
                Action handler = () =>
                {
                    UpdateData();
                    //ToAny("IPCPages.PageNeedAttention");
                    
                };

                MainPage?.Invoke(handler);
                ToNext();
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
                MsgBox.Show($"解析读取身份证信息结果发生了异常:\n{ex.Message}");
            }
        }

        private void OnReadFailed(string outParams, string error)
        {
            StopWork();
            string msg = string.Format("身份证信息读取错误: \n{0}", error);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                ToHome();
            };
            for (int i = 0; i < Pages.Count; i++)
            {
                Pages[i]?.Invoke(handler, msg);
            }
        }

        private void OnReadTimeout(string outParams)
        {
            StopWork();
            string msg = string.Format("读取身份证信息超时: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                ToHome();
            };
            for (int i = 0; i < Pages.Count; i++)
            {
                Pages[i].Invoke(handler, msg);
            }
        }

        private void OnCatchException(string outParams)
        {
            StopWork();
            string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                ToHome();
            };
            MainPage?.Invoke(handler, msg);
        }

        /// <summary>
        /// 保存身份证信息，用于预受理
        /// </summary>
        private void SetSFZData()
        {
            SFZInfo info = new SFZInfo();
            info.Address = IDCardInfo.address.Trim();
            info.BirthDate = IDCardInfo.birthday;
            info.ExpiryDate = IDCardInfo.validtermOfStart + "-" + IDCardInfo.validtermOfEnd;
            info.HeaderPicturePath = IDCardInfo.HeadImage;
            info.IsManualInputNumberVerify = IDCardInfo.IsManualInputNumberVerify;
            info.IssueUnit = IDCardInfo.signdate;
            info.Name = IDCardInfo.name.Trim();
            info.Nation = IDCardInfo.people;
            info.Sex = IDCardInfo.sex;
            info.SFZH = IDCardInfo.number;
            info.ExpiryStartDate = IDCardInfo.validtermOfStart; ;
            info.ExpiryEndDate = IDCardInfo.validtermOfEnd;
            info.SFZZM = IDCardInfo.FrontImage;
            info.SFZBM = IDCardInfo.BackImage;
            SetValue("SFZInfo", info);
        }
    }
}
